﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Caching;
using System.Web.Hosting;

namespace Wedn.TemplateEngine.UC
{
    public class TemplatePathProvider : VirtualPathProvider
    {
        Hashtable virtualFiles = null;
        public TemplatePathProvider() : base() { }

        private bool IsPathVirtual(string virtualPath)
        {
            string checkPath = VirtualPathUtility.ToAppRelative(virtualPath);
            return checkPath.StartsWith("~/template", StringComparison.InvariantCultureIgnoreCase);
        }

        public override bool FileExists(string virtualPath)
        {
            if (IsPathVirtual(virtualPath))
            {
                return true;
                //TemplateVirtualFile file = (TemplateVirtualFile)GetFile(virtualPath);
                //return file.Exists;
            }
            else
                return Previous.FileExists(virtualPath);
        }

        //public override bool DirectoryExists(string virtualDir)
        //{
        //    if (IsPathVirtual(virtualDir))
        //    {
        //        return true;
        //        //TemplateVirtualFile file = (TemplateVirtualFile)GetFile(virtualPath);
        //        //return file.Exists;
        //    }
        //    else
        //        return Previous.FileExists(virtualDir);
        //}

        public override VirtualFile GetFile(string virtualPath)
        {
            if (IsPathVirtual(virtualPath))
                return new TemplateVirtualFile(virtualPath,this);
            else
                return Previous.GetFile(virtualPath);
        }

        public override string GetCacheKey(string virtualPath)
        {
            if (IsPathVirtual(virtualPath))
                return null;
            else
                return Previous.GetCacheKey(virtualPath);
        }

        public override CacheDependency GetCacheDependency(string virtualPath, System.Collections.IEnumerable virtualPathDependencies, DateTime utcStart)
        {
            if (IsPathVirtual(virtualPath))
            {
                string path = HttpRuntime.AppDomainAppPath + virtualPath.Substring(1);
                return new CacheDependency(path);
            }
            else
                return Previous.GetCacheDependency(virtualPath, virtualPathDependencies, utcStart);
        }
    }
}
